<template>
	<base-page class="edit-form base-form" style="width: 100vw" title="发布帖子" @back="onCancel">
		<view class="main-box">
			<view class="content-box">
				<u-form ref="mobileApplyInfoRef" :rules="rules" :model="formData" label-width="120px" label-align="left"
					:errorType="['border-bottom', 'message']">
					<u-row gutter="0">
						<u-col :span="12">
							<view class="mt-16">
								<view class="u-cell-group" style="padding: 5px">
									<u-row gutter="0">
										<u-col :span="12">
											<field-input label="论坛主题" prop="themeFilter" v-model="formData.themeFilter"
												type="textarea" :clearable="true" :disabled="false" :required="false"
												:readonly="false" />

											<field-select label="班级" prop="classIdFilter"
												v-model="formData.classIdFilter" :multiple="false"
												:dataList="classIdFilterWidgetDropdownList" :required="true"
												:disabled="false" />

											<field-select label="老师" prop="teacherIdFilter"
												v-model="formData.teacherIdFilter" :multiple="false"
												:dataList="teacherIdFilterWidgetDropdownList" :required="true"
												:disabled="false" />

											<field-select label="课程" prop="courseIdFilter"
												v-model="formData.courseIdFilter" :multiple="false"
												:dataList="courseIdFilterWidgetDropdownList" :required="true"
												:disabled="false" />

											<field-upload ref="photograph" label="图片" prop="path"
												v-model="formData.path"
												:action="getUploadActionUrl('/admin/mobile/mobileEntry/uploadImage')"
												name="uploadFile" :header="getUploadHeaders" @input="onUploadSuccess"
												:file-list="fileList"
												:formData="{fieldName: 'photograph', asImage: false}"
												:downloadParams="{id: formData.id, fieldName: 'path', asImage: false}"
												:maxCount="9" :disabled="false" :isImage="true" />
										</u-col>
									</u-row>
								</view>
							</view>
						</u-col>
					</u-row>
				</u-form>
			</view>
		</view>
		<view class="menu-box">
			<u-button :custom-style="{width: '100%'}" style="flex-grow: 1; margin-left: 8px" type="primary"
				size="medium" @click="onAddClick()">
				发布帖子
			</u-button>
		</view>

		<u-modal v-model="show" :content="content" show-cancel-button @cancel="onCancel()" confirm-text="取消"
			cancel-text='返回'></u-modal>

	</base-page>
</template>

<script>
	import {
		showMessage,
		getToken
	} from '@/utils';
	import {
		CourseInfoController,
		Leader
	} from '@/api';
	import {
		uploadMixin,
		statsDateRangeMixin
	} from '@/utils/mixins';
	import projectConfig from '@/core/config'
	export default {
		name: 'mobileApplyInfo',
		mixins: [uploadMixin, statsDateRangeMixin],
		data() {
			return {
				show: false,
				content: '',
				formData: {
					// id
					id: undefined,
					// 班级id
					classId: undefined,
					// 姓名
					name: undefined,

					officerId: undefined,
					// 手机号码
					path: undefined,
					themeFilter: '',
					classIdFilter: '',
					teacherIdFilter: '',
					courseIdFilter: '',

				},

				classIdFilterWidgetDropdownList: [],
				teacherIdFilterWidgetDropdownList: [],
				courseIdFilterWidgetDropdownList: [],

				classIdWidget: [],
				ganbuWidget: {},
				rules: {
					'themeFilter': [{
						required: true,
						message: '请输入论坛主题内容',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'classIdFilter': [{
						required: true,
						message: '请选择班级',
						trigger: 'blur',
						transform: (value) => String(value)
					}],

					'teacherIdFilter': [{
						required: true,
						message: '请选择老师',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'courseIdFilter': [{
						required: true,
						message: '请选择课程',
						trigger: 'blur',
						transform: (value) => String(value)
					}],

				},
				fileList: []

			}
		},
		mounted() {
			this.ininList();
			if (this.$refs.mobileApplyInfoRef) this.$refs.mobileApplyInfoRef.setRules(this.rules);
		},
		computed() {},
		methods: {
			ininList() {
				Leader.classInfolistDict(this).then((res) => {
					this.classIdFilterWidgetDropdownList = res
				}).catch((e) => {
					console.log(e);
				})
				Leader.teacherInfolistDict(this).then((res) => {
					this.teacherIdFilterWidgetDropdownList = res
				}).catch((e) => {
					console.log(e);
				})
				Leader.courseInfolistDict(this).then((res) => {
					this.courseIdFilterWidgetDropdownList = res
				}).catch((e) => {
					console.log(e);
				})
			},
			objectToQueryString(params) {
				if (params == null) {
					return null;
				} else {
					return Object.keys(params)
						.map(key => {
							if (params[key] !== undefined) {
								return `${key}=${params[key]}`;
							} else {
								return undefined;
							}
						})
						.filter(item => item != null)
						.join('&');
				}
			},
			buildGetUrl(actionName, params) {
				const queryString = this.objectToQueryString(params);
				if (actionName != null && actionName !== '') {
					if (actionName.substring(0, 1) === '/') actionName = actionName.substring(1);

					return (
						projectConfig.baseUrl + actionName + (queryString == null ? '' : '?' + queryString)
					);
				}
			},
			getUploadFileUrl(item, params) {

				if (item == null || item.downloadUri == null) {
					return null;
				} else {

					const query = {};
					query.Authorization = getToken();
					query.filename = params

					return this.buildGetUrl(item.downloadUri, query);
				}
			},
			onUploadSuccess(data, index, fileList, name) {
				this.fileList = []
				this.fileList.push({
					src: this.getUploadFileUrl(JSON.parse(data)[0], JSON.parse(data)[0].filename)
				})
				this.formData.path = (data)
				console.log(this.formData.path);
				console.log(this.fileList.src);

			},
			onCancel() {
				uni.navigateBack();
			},

			changeGan(val, val2) {
				this.formData.officerId = val2.id
				this.formData.jobTitle = val2.jobTitle
				this.formData.name = val2.name
				this.formData.phone = val2.phone
			},
			/**
			 * 提交
			 */
			onAddClick() {
				const files = JSON.parse(this.formData.path);
				// 处理所有文件
				const imgList = files.map(file => ({
					filePath: `${projectConfig.baseUrl}${file.downloadUri.slice(1)}?filename=${file.filename}&Authorization=${getToken()}`
				}));
				this.$refs.mobileApplyInfoRef.validate((valid) => {
					if (!valid) return;
					let params = {
						courseForumDto: {
							theme: this.formData.themeFilter,
							classId: this.formData.classIdFilter,
							teacherId: this.formData.teacherIdFilter,
							courseId: this.formData.courseIdFilter,
							courseForumFiles: imgList || [],
						}
					};

					Leader.courseForumAdd(this, params).then((res) => {
						this.show = true;
						if (res) {
							this.content = "发布成功"
						} else {
							this.content = "发布失败"
						}

					}).catch((e) => {
						console.log(e);
					})

				})
			}
		}
	};
</script>

<style scoped></style>